package solution.tree;

import lombok.ToString;

@ToString()
public class TreeNode {
    public long no;
    public String name;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(long no, String name) {
        this.no = no;
        this.name = name;
    }

    public void pre() {
        System.out.println("rootName:" + this.name + "  rootNo:" + this.no);
        if (this.left != null) {
            System.out.println("left: " + this.left);
            this.left.pre();
        }
        if (this.right != null) {
            System.out.println("right: " + this.right);
            this.right.pre();
        }
    }

    public void middle() {
        if (this.left != null) this.left.middle();
        if (this.right != null) this.right.middle();
    }

    public void end() {
        if (this.left != null) this.left.end();
        if (this.right != null) this.right.end();
    }

    public TreeNode findByPre(long no) {
        if (this.no == no) return this;
        TreeNode temp = null;
        if (this.left != null) temp = this.left.findByPre(no);
        if (temp != null) return temp;
        if (this.right != null) temp = this.right.findByPre(no);
        return temp;
    }

    public TreeNode findByMiddle(long no) {
        TreeNode temp = null;
        if (this.left != null) temp = this.left.findByMiddle(no);
        if (temp != null) return temp;
        if (this.no == no) return this;
        if (this.right != null) temp = this.right.findByMiddle(no);
        return temp;
    }

    public TreeNode findByEnd(long no) {
        TreeNode temp = null;
        if (this.left != null) temp = this.left.findByEnd(no);
        if (temp != null) return temp;
        if (this.right != null) temp = this.right.findByEnd(no);
        if (temp != null) return temp;
        if (this.no == no) return this;
        return null;
    }

    public TreeNode transfer(TreeNode treeNode) {
        if (treeNode == null) return null;
        TreeNode temp = treeNode.left;
        treeNode.left = treeNode.right; //左子树赋给右子树
        treeNode.right = temp; //右子树赋给左子树
        transfer(treeNode.left);
        transfer(treeNode.right);
        return treeNode;
    }

}
